/*
 * @Descripttion:
 * @version:
 * @Author: cxguo
 * @Date: 2019-06-28 14:53:52
 * @LastEditors: cxguo
 * @LastEditTime: 2020-11-06 16:54:47
 */
import axios from 'axios'
import { getToken } from '@/utils/auth' // 验权
import { Notification } from 'element-ui'

const addErrorLog = errorInfo => {
  // const { statusText, status, request: { responseURL }} = errorInfo
  // const info = {
  //   type: 'ajax',
  //   code: status,
  //   mes: statusText,
  //   url: responseURL
  // }
  // if (!responseURL.includes('save_error_logger')) store.dispatch('addErrorLog', info)
  // store.dispatch('addErrorLog', info)
}

const handleErrorStatus = (error) => {
  return error.response
}

class HttpRequest {
  constructor(baseUrl) {
    this.baseUrl = baseUrl
    this.queue = {}
  }
  getInsideConfig() {
    const config = {
      baseURL: this.baseUrl,
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'X-URL-PATH': location.pathname,
        'Access-Control-Allow-Origin': '*',
        'token': getToken()
      }
    }
    return config
  }
  destroy(url) {
    delete this.queue[url]
    // if (!Object.keys(this.queue).length) {}
  }
  interceptors(instance, url) {
    // 请求拦截
    instance.interceptors.request.use(config => {
      this.queue[url] = true
      return config
    }, error => {
      return Promise.reject(error)
    })
    // 响应拦截
    instance.interceptors.response.use(res => {
      this.destroy(url)
      if (!res.data.flag) {
        const title = res.data.title || '请求异常'
        const message = res.data.message
        Notification.error({ title, message: message })
      }
      const { data, status, headers } = res
      return { data, status, headers }
    }, error => {
      // console.log('响应拦截 error', error)
      if (!error.response) return console.log(error)
      if (error.response.status !== 200) {
        return handleErrorStatus(error)
      } else {
        // 将后端错误记录到日志中去
        this.destroy(url)
        let errorInfo = error.response
        if (!errorInfo) {
          const { request: { statusText, status }, config } = JSON.parse(JSON.stringify(error))
          errorInfo = {
            statusText,
            status,
            request: { responseURL: config.url }
          }
        }
        addErrorLog(errorInfo)
        return Promise.reject(error)
      }
    })
  }
  request(options) {
    const instance = axios.create({ timeout: 120000 })
    options = Object.assign(this.getInsideConfig(), options)
    this.interceptors(instance, options.url)
    return instance(options)
  }
}
export default HttpRequest
